<?php
class fw_Db{

/**  
* 查询总次数  
*  
* @var int  
*/  
 public $querynum = 0;  
/**  
* 连接句柄  
*  
* @var object  
*/  
 public $link;  

 public $fieldType=array();

/*
表前缀
@var string 下面方法需要在配置文件中配置TB_EX 作为表的前缀
*/



public function add_ex($tb){
	return TB_EX.$tb_ex.$tb;
}

 /*mysql数据库是否使用严格的类型(mysql类型没开启自动转换)默认为false,表示mysql有开启类型转换,这个变量目前只要是用于insert函数的单引号在没有自动转换的mysql里面的问题,可能将来会增加相关函数
 */
public $is_type_tight=false;

function fw_Db(){
	$param = Fw::app()->param["db"];
	$this->connect($param["host"], $param["user"], $param['password'],$param['dbname']);
}

/**  
* 构造函数  
*  
* @param string $dbhost 主机名  
* @param string $dbuser 用户  
* @param string $dbpw 密码  
* @param string $dbname 数据库名  
* @param int $pconnect 是否持续连接  
*/  
public function connect($dbhost, $dbuser, $dbpw, $dbname = "",$dbcharset="utf-8", $pconnect = 0) {  
	if($pconnect) { 
		if(!$this->link = @mysql_pconnect($dbhost, $dbuser, $dbpw)) {  
			$this->halt("Can not connect to MySQL server");  
		}  
	} else {  
		if(!$this->link = @mysql_connect($dbhost, $dbuser, $dbpw)) {  
			$this->halt("Can not connect to MySQL server");  
		}  
	}  
	if($this->version() > "4.1") {   
		if($dbcharset) {  
			mysql_query("SET character_set_connection={$dbcharset}, character_set_results=$dbcharset, character_set_client=binary", $this->link);  
		}  
		if($this->version() > "5.0.1") {  
			mysql_query("SET sql_mode=''", $this->link);  
		}  
	}  
	if($dbname) {  
		mysql_select_db($dbname, $this->link);  
	} 
}  
/**  
* 选择数据库  
*  
* @param string $dbname  
* @return   
*/  
public function select_db($dbname) {  
   return mysql_select_db($dbname, $this->link);  
} 

/**  
* 取出结果集中一条记录  
*  
* @param object $query  
* @param int $result_type  
* @return array  
*/  
public function fetch_array($query, $result_type = MYSQL_ASSOC) {  //默认只取关联数组 不取数字数组.
return mysql_fetch_array($query, $result_type);  
}  
 
/**  
* 查询SQL  
*  
* @param string $sql  
* @param string $type  
* @return object  
*/  
public function query($sql, $type = "") {  
 $func = $type == "UNBUFFERED" && @function_exists("mysql_unbuffered_query") ? "mysql_unbuffered_query" : "mysql_query";  
if(!($query = $func($sql, $this->link)) && $type != "SILENT") {  
	$this->halt("MySQL Query Error", $sql);  
}  
$this->querynum++;  
return $query;  
}

/**
 * SQL 查询
 * @param string $sql
 * @return array
 */
public  function findBySql($sql){
	 $rs = $this->query($sql);
	 $re=array();
	 if($this->num_rows($rs)>=1){
	 	while($info = $this->fetch_array($rs)){
	 		$re[]=$info;
	 	}
	 }
	 $this->free_result($rs);
	 return $rs;
}

/**  
* 取影响条数  
*  
* @return int  
*/  
public function affected_rows() {  
	return mysql_affected_rows($this->link);  
} 

/**  
* 返回错误信息  
*  
* @return array  
*/  
public function error() {  
	return (($this->link) ? mysql_error($this->link) : mysql_error());  
} 

/**  
* 返回错误代码  
*  
* @return int  
*/  
public function errno() {  
	return intval(($this->link) ? mysql_errno($this->link) : mysql_errno());  
}  
/**  
* 返回查询结果  
*  
* @param object $query  
* @param string $row  
* @return mixed  
*/  
public function result($query, $row,$flname=0) {  
	$query = @mysql_result($query, $row,$flname);  
	return $query;  
}  
/**  
* 结果条数  
*  
* @param object $query  
* @return int  
*/  
public function num_rows($query) {  
	$query = mysql_num_rows($query);  
	return $query;  
}  
/**  
* 取字段总数  
*  
* @param object $query  
* @return int  
*/  
public function num_fields($query) {  
return mysql_num_fields($query);  
}  
/**  
* 释放结果集  
*  
* @param object $query  
* @return bool  
*/  
public function free_result($query) {  
	return @mysql_free_result($query);  
}  
/**  
* 返回自增ID  
*  
* @return int  
*/  
public function insert_id() {  
	return ($id = mysql_insert_id($this->link)) >= 0 ? $id : $this->result($this->query("SELECT last_insert_id()"), 0);  
}  
/**  
* 从结果集中取得一行作为枚举数组  
*  
* @param object $query  
* @return array  
*/  
public function fetch_row($query) {  
	$query = mysql_fetch_row($query);  
	return $query;  
}

/**  
* 从结果集中取得列信息并作为对象返回  
*  
* @param object $query  
* @return object  
*/  
public function fetch_fields($query) {  
	return mysql_fetch_field($query);  
}  

public function select_affectedt_rows($rs){
	 return mysql_affected_rows($rs,$this->link);
	
}
/**  
* 返回mysql版本  
*  
* @return string  
*/  
public function version() {  
	return mysql_get_server_info($this->link);  
}  
/**  
* 关闭连接  
*  
* @return bool  
*/  
public function close() {  
	return mysql_close($this->link);  
}  
/**  
* 输出错误信息  
*  
* @param string $message  
* @param string $sql  
*/  
public function halt($message = "", $sql = "") {
	 @header("Content-type: text/html; charset=utf-8");
	 
	if (DEBUG==1){
		$debug = debug_backtrace();
		echo $message . "\r\n<br/>SQL--> " . $sql."\r\n<br/>ERROR_MESSAGE-->".$this->error().
		"\r\n<br/>--------------debug--------------\r\n<br/>";
		$this->echoarray($debug);
		echo "\r\n<br/>-------------debug end----------------";  
		
  	}else{
		echo 'SQL Error';
	}
	@$this->rollback();
	exit;
}  
/////////////////////////////以下是扩展的sql方法.//////
/* 把数组按照 key value value 的对应关系插入数据表table中
table 要插入的数据表
要注意 这些扩展方法是没自己给表有加前缀的.
*/
public function insert($table,$array){
	$temp="";$temp2='';
	foreach($array as $key=>$value){
		if($this->is_type_tight){
			if(is_string($value)){
				$temp .="`$key`,";$temp2 .="'$value',";
			}elseif(is_int($value||is_null($value)||is_float($value))){
				$value+=0;
				$temp .="`$key`,";$temp2 .="'$value',";
			}
		}else{
			$temp .="`$key`,";$temp2 .="'$value',";
		}
	}
	$temp = substr($temp,0,strlen($temp)-1);
	$temp2 = substr($temp2,0,strlen($temp2)-1);
	
	$sql = "INSERT INTO `$table` ($temp) VALUE($temp2)";
	return $this->query($sql);
}

/**
 * 
 * @param string $table
 * @param string $where
 * @return object
 */
public function del($table,$where){
	$sql = "DELETE FROM `{$table}` where {$where}";
	return $this->query($sql);
}

/**
*
**/
public function update($table,$array,$where){
	foreach ($array as $key=>$value){
		$temp .= "`$key`='$value',";
	}
	$temp = substr($temp,0,strlen($temp)-1);
	$sql = "update `{$table}` set ($temp) where {$where} ";
	return $this->query($sql);
}

public function findOne($tableName,$wh=null){
	  $data = array();
	  if(!empty($wh)){
	  	$data = $this->select($tableName,$wh,"limit:1");
	  
	  }else{
	  	$data = $this->select($tableName,"limit:1");
	  }
	  if(!empty($data)){ 
	  	return $data[0];
	  }else{
	  	return null;
	  }
}


/**
 * 进行数据库查询select 参数不定
 * 参数说明:所有参数必须是string
 * 第一个参数必须是表名;
 * 从第二个参数起,
 * 如果是写上 "where:XXX" 则认为是where条件;
 * 如果写上 "xxx" 则认为是键值
 * 如果写上 "by:XXX" 则认为是排序
 * 如果写上 "limit:xxx,xxx" 则认为是分页
 * #参数不正确则返回false; 成功查询返回查询后的数组;
 * @access	public
 * @return boolean|multitype:multitype:
 */
public function select(){
	$numargs = func_num_args();//获取参数个数;
	$where = "";$key="";$limit="";$by="";
	if($numargs==0){return false;}
	//echo $numargs;
	if($numargs>=2){
		$arg_list = func_get_args();
		$table = $arg_list[0];
		unset($arg_list[0]);
	//	print_r($arg_list);
		foreach($arg_list as $k=>$value){
			if(preg_match("#^(where:)\w#",$value)){
				$temp = explode(":",$value);
					$where = "WHERE {$temp[1]} " ;
			}elseif(preg_match("#^by:\w#",$value)){
				$temp = explode(":",$value);
				$by = "order by {$temp[1]}" ;
			}elseif(preg_match("#^limit:\w#",$value)){
				$temp = explode(":",$value);
				$limit = "limit {$temp[1]}";
			}else{
				$key .= "$value,";
			}
		}
		
		if($key==""){
			$key = "*";
		}else{
			$key =substr($key,0,strlen($key)-1); 
		}
		
	$sql_base = "SELECT $key FROM `$table`";
	}
	if(!empty($where)){
		$sql_base .= " $where";
	}
	if(!empty($by)){
		$sql_base .= " $by";
	}
	if(!empty($limit)){
		$sql_base .= " $limit";
	}
	//var_dump($sql_base);
	$rs = $this->query($sql_base);
	$re=array();
	if($this->num_rows($rs)>=1){
		while($info = $this->fetch_array($rs)){
			$re[]=$info;
		}
	}
	$this->free_result($rs);
	return $re;
	}
	
	
	/**
	 * 回滚事务
	 **/
	public function rollback(){
		$this->query('rollback');
	}
	/**
	 * 开始事务
	 */
	public function begin(){
		$this->query('SET AUTOCOMMIT = 0'); //停用自动提交;
		$this->query('BEGIN') ;//开始一个事务;
	}
	
	/**
	 * 提交事务
	 */
	public function commit(){
		$this->query('commit');
	}


 	public function echoarray($array){
		foreach($array as $k=>$v ){
			if(is_array($v)){
				if(is_array($v)){
					echo "<hr/>";
					$this->echoarray($v);
				}
			}else{
				if($k==='line')
				echo "<b style='color:red'>$k -> " .$v."</b>  ";
				else{
				#echo "$k -> " .$v."  ";
				}
			}
		}
	}

	public function get_server_info(){
		return mysql_get_server_info();
	}

	/**
	 * @access	public
	 * @param	resource
	 * @return	void
	 */
	public function _close($conn_id){
		@mysql_close($conn_id);
	}

	/**
	 *  创建表
	 *  @access	public
	 *  @param $tableName string 表名
	 *  @param $fields array();  字段 (字段array('name'=>'',type='int','length'=>'','primary_key'=>1,'auto_increment'=>1))
	 *  @return boole
	 */
	public function createTable($tableName,$fields){
		   $fieldList = array();
		   $sql = "create table `{$tableName}` (";
		   	foreach ($fields as $key => $value) {
		   		$temp = "`".$value['name']."` ";
		   		$temp .= $value["type"];
		   		if(!empty($value["length"])) $temp .="({$value['length']}) ";
		   		if(!empty($value["auto_increment"])) $temp .= " not null auto increment ";
		   		
		   		if(!empty($value['primary_key'])) $temp .= "primary key";
		   		$fieldList[] = $temp;
		   	}
            $sql .= implode(",",$fieldList);
			$sql .=") ENGINE=InnoDB DEFAULT CHARSET=utf8";
		   return  	$this->query($sql);
	}
    
	
	/**
	 * 添加字段
	 * @access	public
	 * @param string $tablename
	 * @param array $field
	 * @return boole
	 */
	public function addField($tableName,$field){
		$sql =  "ALTER TABLE `{$tableName}` ADD  COLUMN " ;
		$sql .= "`".$field['name']."`";
		$sql .= empty($field['type'])?'': $field['type'];
		$sql .= empty($field["length"])?'':"({$field["length"]})";
		return  $this->query($sql);
	}

    /**
     * 删除表
     * @access public 
     * @param string $tablename
     * @return boole
     */
	public function deleteTable($tablename){
        $sql = "DROP TABLE `".$tablename."`";
        return $this->query($sql);
	}
	
    

	/**
	 * 修改字段
	 * @access	public
	 * @param string $tableName
	 * @param array $field
	 * @return boole
	 */
	public function updateField($tableName,$fieldName,$field){
           $sql = "ALTER TABLE `{$tableName}` CHANGE `{$fieldName}` ";
           $sql .= "`{$field["name"]}`";
           $sql .= empty($field["type"])?"":$field["type"];
           $sql .= empty($field["length"])?'':"({$field["length"]})";
           return $this->query($sql);
	}
	
    /**
     * 删除字段
     * @access	public
     * @param string $tableName 表名
     * @param string $fieldName 要删除的字段名
     * @return boole 
     */
	public function deleteField($tableName,$fieldName){
		 $sql ="ALTER TABLE `{$tableName}` DROP COLUMN `{$fieldName}`";
		 return $this->query($sql);
	}
	
}